<template>
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
    <el-breadcrumb-item :to="{ path: '/' }">
      <i class="el-icon-s-promotion"></i> 后台管理
    </el-breadcrumb-item>
    <el-breadcrumb-item>订单管理</el-breadcrumb-item>
    <el-breadcrumb-item v-for="item in history" :key="item.id"><span v-text="item.name"></span></el-breadcrumb-item>
  </el-breadcrumb>
  <el-divider></el-divider>

  <!-- 数据表格 -->
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
    <el-table-column prop="orderNumber" label="订单号" width="150px" align="center"></el-table-column>
    <el-table-column label="封面图片" width="100" align="center">
      <template slot-scope="scope">
        <el-image
            style="width: 80px; height: 80px"
            :src="JSON.parse(scope.row.productImage)[0].url"
            fit="fit"></el-image>
      </template>
    </el-table-column>
    <el-table-column prop="productName" label="商品名称" width="200" align="center"
                     :show-overflow-tooltip="true"></el-table-column>
    <el-table-column prop="price" label="合计金额" width="200" align="center"></el-table-column>
    <el-table-column prop="userId" label="用户名称" width="200" align="center"></el-table-column>
    <el-table-column prop="stateId" label="订单状态" width="200" align="center">
      <template slot-scope="scope">
        <el-select v-model="scope.row.stateId" :disabled="isDisabled(scope.row)" @change="updateOrderState(scope.row)">
          <el-option
              v-for="stats in filteredStatsOptions(scope.row.stateId)"
              :key="stats.id"
              :label="stats.stateName"
              :value="stats.id"
          ></el-option>
        </el-select>
      </template>
    </el-table-column>
    <el-table-column prop="gmtCreate" label="下单时间" width="200" align="center"></el-table-column>
  </el-table>

  <div style="margin: 50px 0; text-align: right;">
    <el-pagination
        @current-change="changePage"
        :hide-on-single-page="true"
        :page-size="pageSize"
        :current-page="currentPage"
        layout="total, prev, pager, next"
        :total="total">
    </el-pagination>
  </div>

</div>
</template>

<script>
export default {
  data(){
    return{

      statsOptions: [],

      history: [],

      tableData: {
        pictures: '[]',
      },

      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      pageSize: 5,
      pageCount: 1,
      total: 0,

    }
  },
  methods:{

    goBack() {
      console.log('goBack, start...');
      for (let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')

      let parentCategory = this.history[this.history.length - 1];
      this.currentParentId = parentCategory.parentId;
      this.loadOrderList();
      this.history.pop();

      console.log('goBack, done.');
      for (let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')
    },

    isDisabled(selectedRow) {
      const selectedStateId = selectedRow.stateId;
      return (selectedStateId === 6 || selectedStateId === 7);
    },

    //通过下拉框修改訂單的状态
    updateOrderState(rowData) {
      let selectedStateId = rowData.stateId;
      let orderId = rowData.id;
      let selectedStateName = this.statsOptions.find((stats) => stats.id === selectedStateId)?.stateName;

      let url = 'http://localhost:14001/orders/updateState';
      let params = {
        orderId: orderId,
        stateId: selectedStateId
      };

      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .post(url, null, {params: params}).then((response) => {
        // 处理请求成功的逻辑
        this.$alert(response.data.message, '修改成功', {
          confirmButtonText: '确定',
          callback: action => {
            this.loadOrderList()
          }
        });
      }).catch((error) => {
        // 处理请求失败的逻辑
        this.$alert(error.response.data.message, '修改失败', {
          confirmButtonText: '确定',
          callback: action => {
            // 回调函数中的逻辑
          }
        });
      });
    },

    // 切换分页
    changePage(page) {
      this.$router.replace('?page=' + page);
      this.loadOrderList();
    },

    //加载状态栏数据
    loadStateList() {
      let url = 'http://localhost:14001/state/list';
      console.log('url = ' + url);

      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        this.statsOptions = jsonResult.data;
        this.stateListLoaded = true; // 设置状态列表加载完成的标志为true
      });
    },

    //加载订单页面
    loadOrderList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = 'http://localhost:14001/orders/list?pageNum=' + page;
      console.log('url = ' + url);

      let localJwt = JSON.parse(localStorage.getItem('localJwt'));

      this.axios
          .create({
            'headers': {
              'Authorization': localJwt.token
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000) {
          this.tableData = jsonResult.data.list;
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          this.pageCount = jsonResult.data.maxPage;
          this.total = jsonResult.data.total;
        }
      });
    },
  },
  mounted() {
    this.loadOrderList();
    this.loadStateList()
  },
  computed: {
    filteredStatsOptions() {
      return (selectedStateId) => {
        if (selectedStateId >= 3 && selectedStateId <= 7) {
          if (selectedStateId === 5) {
            return this.statsOptions.filter((option) => option.id >= 5 && option.id <= 6);
          } else {
            return this.statsOptions.filter((option) => option.id >= 3 && option.id <= 7);
          }
        } else {
          return [];
        }
      };
    },
  }
}
</script>